#include "headfiles.h"

using namespace std;

#define EPSN 1.0e-9f

bool lineIntersect(float x11, float y11, float x12, float y12,
                   float x21, float y21, float x22, float y22) {
    // If line 1 is vectical
    if (x11 - x12 < EPSN && x11 - x12 > (-1.0f) * EPSN) {
        // If line 2 is also vertical 
        if (x21 - x22 < EPSN && x21 - x22 > (-1.0f) * EPSN) {
            if (x11 - x21 < EPSN && x11 - x21 > (-1.0f) * EPSN) {
                // They are overlap
                return true;
            }
            // Two lines are parallel
            else {
                return false;
            }
        }
        // Line 2 is not vertical
        else {
            return true;
        }
    }
    // Line 1 is not vertical
    else {
         // If line 2 is vertical 
        if (x21 - x22 < EPSN && x21 - x22 > (-1.0f) * EPSN) {
            return true;
        }
        else {
            float slope1 = (y12 - y11) / (x12 - x11);
            float slope2 = (y22 - y21) / (x22 - x21);
            // parallel
            if (slope1 - slope2 < EPSN && slope1 - slope2 > (-1.0f) * EPSN) {
                float c1 = (y11 * x12 - y12 * x11) / (x12 - x11);
                float c2 = (y21 * x22 - y22 * x21) / (x22 - x21);
                if (c1 - c2 < EPSN && c1 - c2 > (-1.0f) * EPSN) {
                    return true;
                }
                else {
                    return false;
                }
            }
            // non-parallel
            else {
                return true;
            }
        }
    }
}

